<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>系统管理功能测试</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .container {
            background: white;
            border-radius: 12px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
            max-width: 900px;
            width: 100%;
            padding: 40px;
        }
        h1 {
            color: #333;
            margin-bottom: 10px;
        }
        .subtitle {
            color: #666;
            margin-bottom: 30px;
        }
        .test-section {
            margin-bottom: 30px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
            border-left: 4px solid #667eea;
        }
        .test-section h3 {
            color: #333;
            margin-bottom: 15px;
        }
        .test-item {
            padding: 12px 0;
            border-bottom: 1px solid #e0e0e0;
        }
        .test-item:last-child {
            border-bottom: none;
        }
        .test-label {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .status-icon {
            font-size: 20px;
        }
        .status-text {
            font-weight: 500;
            color: #666;
        }
        .status-result {
            margin-top: 8px;
            padding: 8px 12px;
            border-radius: 4px;
            font-size: 13px;
            font-family: 'Courier New', monospace;
        }
        .success {
            background: #d4edda;
            color: #155724;
        }
        .error {
            background: #f8d7da;
            color: #721c24;
        }
        .warning {
            background: #fff3cd;
            color: #856404;
        }
        .info {
            background: #d1ecf1;
            color: #0c5460;
        }
        .btn {
            background: #667eea;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 6px;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.3s;
            margin: 10px 10px 10px 0;
        }
        .btn:hover {
            background: #5568d3;
            transform: translateY(-2px);
        }
        .btn-success {
            background: #28a745;
        }
        .btn-success:hover {
            background: #218838;
        }
        .highlight-box {
            background: #fff3cd;
            border: 2px solid #ffc107;
            padding: 15px;
            border-radius: 8px;
            margin: 20px 0;
        }
        .highlight-box h4 {
            color: #856404;
            margin-bottom: 10px;
        }
        .code-block {
            background: #f8f9fa;
            padding: 12px;
            border-radius: 4px;
            font-family: 'Courier New', monospace;
            font-size: 13px;
            margin: 10px 0;
            overflow-x: auto;
        }
        .checklist {
            list-style: none;
            padding: 0;
        }
        .checklist li {
            padding: 8px 0;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .checklist li:before {
            content: "□";
            font-size: 20px;
            color: #666;
        }
        .checklist li.checked:before {
            content: "✓";
            color: #28a745;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🧪 系统管理功能测试</h1>
        <p class="subtitle">快速验证系统管理修复是否成功</p>

        <div class="highlight-box">
            <h4>⚠️ 重要：测试前必须操作</h4>
            <p>由于修改了登录逻辑，<strong>必须重新登录</strong>才能看到"新建管理员"按钮！</p>
            <ol style="margin: 10px 0 0 20px; line-height: 1.8;">
                <li>清除浏览器缓存（Cmd/Ctrl + Shift + R）</li>
                <li>访问 <a href="http://localhost:3308" target="_blank">http://localhost:3308</a></li>
                <li>使用 admin/admin 重新登录</li>
            </ol>
        </div>

        <div class="test-section">
            <h3>📡 API测试</h3>
            <div class="test-item">
                <div class="test-label">
                    <span class="status-icon" id="api-login-icon">⏳</span>
                    <span class="status-text">1. 登录API</span>
                </div>
                <div class="status-result info" id="api-login-result">待测试...</div>
            </div>
            <div class="test-item">
                <div class="test-label">
                    <span class="status-icon" id="api-users-icon">⏳</span>
                    <span class="status-text">2. 后台用户列表API</span>
                </div>
                <div class="status-result info" id="api-users-result">待测试...</div>
            </div>
            <div class="test-item">
                <div class="test-label">
                    <span class="status-icon" id="api-roles-icon">⏳</span>
                    <span class="status-text">3. 角色列表API</span>
                </div>
                <div class="status-result info" id="api-roles-result">待测试...</div>
            </div>
            <div class="test-item">
                <div class="test-label">
                    <span class="status-icon" id="api-stats-icon">⏳</span>
                    <span class="status-text">4. 统计数据API</span>
                </div>
                <div class="status-result info" id="api-stats-result">待测试...</div>
            </div>
            <button class="btn" onclick="testAllApis()">🔄 测试所有API</button>
        </div>

        <div class="test-section">
            <h3>✅ 前端功能验证清单</h3>
            <p style="margin-bottom: 15px; color: #666;">请在浏览器中手动验证以下功能：</p>
            <ul class="checklist">
                <li>访问系统管理菜单能正常展开</li>
                <li>点击"后台用户管理"页面能正常加载</li>
                <li>能看到统计卡片（管理员总数等）</li>
                <li><strong>能看到"新建管理员"按钮（绿色）</strong></li>
                <li>点击"新建管理员"能打开对话框</li>
                <li>对话框中能看到角色下拉选项</li>
                <li>能看到编辑、禁用、重置密码、删除按钮</li>
                <li>浏览器控制台没有404错误</li>
            </ul>
        </div>

        <div class="test-section">
            <h3>🔍 调试检查</h3>
            <div class="test-item">
                <div class="test-label">
                    <span class="status-icon" id="debug-storage-icon">⏳</span>
                    <span class="status-text">localStorage 用户信息检查</span>
                </div>
                <div class="status-result info" id="debug-storage-result">待检查...</div>
            </div>
            <div class="test-item">
                <div class="test-label">
                    <span class="status-icon" id="debug-roles-icon">⏳</span>
                    <span class="status-text">用户角色检查</span>
                </div>
                <div class="status-result info" id="debug-roles-result">待检查...</div>
            </div>
            <button class="btn" onclick="debugCheck()">🔍 检查本地数据</button>
        </div>

        <div style="margin-top: 30px; text-align: center;">
            <button class="btn btn-success" onclick="openAdmin()">🚀 打开管理后台</button>
            <button class="btn" onclick="clearAndReload()">🔄 清除缓存并刷新</button>
        </div>

        <div class="highlight-box" style="margin-top: 30px;">
            <h4>💡 如果按钮仍然不可见</h4>
            <p>在浏览器控制台执行以下代码检查：</p>
            <div class="code-block">
const userInfo = JSON.parse(localStorage.getItem('userInfo'))
console.log('用户角色:', userInfo?.roles)
// 应该输出: ['SUPER_ADMIN']
            </div>
            <p style="margin-top: 10px;">如果 roles 为空或 undefined，请清除缓存并重新登录！</p>
        </div>
    </div>

    <script>
        let token = '';

        function updateStatus(id, icon, className, text) {
            document.getElementById(id + '-icon').textContent = icon;
            const resultEl = document.getElementById(id + '-result');
            resultEl.className = 'status-result ' + className;
            resultEl.textContent = text;
        }

        async function testLogin() {
            try {
                const response = await fetch('http://localhost:3308/api/web/auth/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        username: 'admin',
                        password: 'admin'
                    })
                });

                const data = await response.json();
                
                if (data.code === 200 && data.data.token) {
                    token = data.data.token;
                    const hasRoles = data.data.roles && data.data.roles.length > 0;
                    
                    updateStatus('api-login', '✅', 'success', 
                        `登录成功！Token已获取\n角色: ${data.data.roles ? data.data.roles.join(', ') : '未找到'}\n${hasRoles ? '✅ 角色数据正常' : '⚠️ 缺少角色数据'}`
                    );
                    return true;
                } else {
                    throw new Error(data.message || '登录失败');
                }
            } catch (error) {
                updateStatus('api-login', '❌', 'error', '登录失败: ' + error.message);
                return false;
            }
        }

        async function testAdminUsers() {
            if (!token) {
                updateStatus('api-users', '⚠️', 'warning', '请先执行登录测试');
                return;
            }

            try {
                const response = await fetch('http://localhost:3308/api/web/admin-users?page=1&pageSize=10', {
                    headers: {
                        'Authorization': 'Bearer ' + token
                    }
                });

                const data = await response.json();
                
                if (data.code === 200) {
                    updateStatus('api-users', '✅', 'success', 
                        `✅ 接口正常！\n用户数: ${data.data.total}\n路径: /api/web/admin-users`
                    );
                } else {
                    throw new Error(data.message || '请求失败');
                }
            } catch (error) {
                updateStatus('api-users', '❌', 'error', '请求失败: ' + error.message);
            }
        }

        async function testRoles() {
            if (!token) {
                updateStatus('api-roles', '⚠️', 'warning', '请先执行登录测试');
                return;
            }

            try {
                const response = await fetch('http://localhost:3308/api/web/role/all', {
                    headers: {
                        'Authorization': 'Bearer ' + token
                    }
                });

                const data = await response.json();
                
                if (data.code === 200) {
                    const roleNames = data.data.map(r => r.name).join(', ');
                    updateStatus('api-roles', '✅', 'success', 
                        `✅ 接口正常！\n角色数: ${data.data.length}\n角色: ${roleNames}`
                    );
                } else {
                    throw new Error(data.message || '请求失败');
                }
            } catch (error) {
                updateStatus('api-roles', '❌', 'error', '请求失败: ' + error.message);
            }
        }

        async function testStatistics() {
            if (!token) {
                updateStatus('api-stats', '⚠️', 'warning', '请先执行登录测试');
                return;
            }

            try {
                const response = await fetch('http://localhost:3308/api/web/admin-users/statistics', {
                    headers: {
                        'Authorization': 'Bearer ' + token
                    }
                });

                const data = await response.json();
                
                if (data.code === 200) {
                    updateStatus('api-stats', '✅', 'success', 
                        `✅ 接口正常！\n管理员总数: ${data.data.totalCount || 0}\n活跃用户: ${data.data.activeCount || 0}`
                    );
                } else {
                    throw new Error(data.message || '请求失败');
                }
            } catch (error) {
                updateStatus('api-stats', '❌', 'error', '请求失败: ' + error.message);
            }
        }

        async function testAllApis() {
            updateStatus('api-login', '⏳', 'info', '测试中...');
            updateStatus('api-users', '⏳', 'info', '等待中...');
            updateStatus('api-roles', '⏳', 'info', '等待中...');
            updateStatus('api-stats', '⏳', 'info', '等待中...');

            const loginSuccess = await testLogin();
            if (loginSuccess) {
                await new Promise(resolve => setTimeout(resolve, 500));
                await testAdminUsers();
                await new Promise(resolve => setTimeout(resolve, 500));
                await testRoles();
                await new Promise(resolve => setTimeout(resolve, 500));
                await testStatistics();
            }
        }

        function debugCheck() {
            try {
                const userInfoStr = localStorage.getItem('userInfo');
                if (!userInfoStr) {
                    updateStatus('debug-storage', '⚠️', 'warning', 
                        '未找到用户信息！请先登录。'
                    );
                    updateStatus('debug-roles', '⚠️', 'warning', '无数据');
                    return;
                }

                const userInfo = JSON.parse(userInfoStr);
                updateStatus('debug-storage', '✅', 'success', 
                    `用户信息存在\n用户ID: ${userInfo.userId}\n昵称: ${userInfo.nickname}\n角色字段: ${userInfo.role}`
                );

                if (userInfo.roles && userInfo.roles.length > 0) {
                    updateStatus('debug-roles', '✅', 'success', 
                        `✅ 角色数据正常！\n角色列表: ${userInfo.roles.join(', ')}\n\n这意味着"新建管理员"按钮应该可见！`
                    );
                } else {
                    updateStatus('debug-roles', '❌', 'error', 
                        `❌ 缺少角色数据！\n\n这就是按钮不可见的原因！\n请清除缓存并重新登录。`
                    );
                }
            } catch (error) {
                updateStatus('debug-storage', '❌', 'error', '数据解析失败: ' + error.message);
                updateStatus('debug-roles', '❌', 'error', '无法检查');
            }
        }

        function openAdmin() {
            window.open('http://localhost:3308', '_blank');
        }

        function clearAndReload() {
            if (confirm('确定要清除所有缓存吗？这将退出登录状态。')) {
                localStorage.clear();
                sessionStorage.clear();
                alert('缓存已清除！请重新访问管理后台并登录。');
            }
        }

        // 页面加载时自动检查
        window.onload = function() {
            setTimeout(debugCheck, 500);
        };
    </script>
</body>
</html>

